package controller

import (
	"net/http"

	"gitee.com/shiwjlinux/blog-web/db"
	"gitee.com/shiwjlinux/blog-web/util"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func DeleteUser(c *gin.Context) {
	claim, _ := util.ParseToken(c.GetHeader("token"))
	name := claim.Name

	user := &db.User{}
	err := c.ShouldBind(user)
	if err != nil {
		logrus.Error("err:", err.Error())
	}

	user = util.AuthUserAndPassword(name, user.Password)
	if user == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "用户名或密码错误",
		})
		return
	}

	db.DB.Delete(&user)
	c.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}

func DeleteComment(c *gin.Context) {
	id := c.Param("id")
	comment := db.GetComment(id)
	claims, _ := util.ParseToken(c.GetHeader("token"))
	name := claims.Name
	if comment.UserID != db.GetUserByName(name).ID {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "权限不足",
		})
		return
	}

	db.DB.Delete(&comment)
	c.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}

func DeleteArticle(c *gin.Context) {
	id := c.Param("id")
	article := db.GetArticle(id)

	claim, _ := util.ParseToken(c.GetHeader("token"))
	name := claim.Name

	if article.UserID != db.GetUserByName(name).ID {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "权限不足",
		})
		return

	}

	// 删除关联分类
	db.DB.Where("article_id=?", id).Delete(&db.ArticleCategory{})
	// 删除关联标签
	db.DB.Where("article_id=?", id).Delete(&db.ArticleTag{})

	db.DB.Delete(&article)
	c.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}
